<template>
  <form>
    <md-card>
      <md-card-header class="md-card-header-icon md-card-header-green">
        <div class="card-icon">
          <md-icon>lock_outline</md-icon>
        </div>
        <h4 class="title">修改密码</h4>
      </md-card-header>

      <md-card-content>
        <div class="md-layout">
          <div class="md-layout-item md-size-100">
            <md-field>
              <label>旧密码</label>
              <md-input v-model="model.oldPassword" type="password"></md-input>
            </md-field>
            <md-field>
              <label>新密码</label>
              <md-input v-model="model.newPassword" type="password"></md-input>
            </md-field>
            <md-field>
              <label>确认密码</label>
              <md-input v-model="model.newPasswordConfirm" type="password"></md-input>
            </md-field>
          </div>
          <div class="md-layout-item md-size-100 text-right">
            <md-button class="md-raised md-success mt-4" @click="updatePassword">更新</md-button>
          </div>
        </div>
      </md-card-content>
    </md-card>
  </form>
</template>

<script>

  import {post} from '@/utils/ajax';
  import * as api from '@/constants/api';
  import auth from '@/utils/auth';
  import * as mutationKeys from '@/constants/mutation-keys';
  import {toast} from "@/utils/tools";

  export default {
    name: "PasswordForm",
    data(){
      return {
        model:{
          oldPassword: '',
          newPassword: '',
          newPasswordConfirm: '',
        }
      }
    },
    methods:{
      updatePassword(){
        let errMsg = '';
        if(!this.model.oldPassword){
          errMsg = '请输入密码'
        }else if(!this.model.newPassword){
          errMsg = '请输入新密码'
        }else if(!this.model.newPasswordConfirm){
          errMsg = '请输入确认密码'
        }else if(this.model.newPassword!==this.model.newPasswordConfirm) {
          errMsg = '新密码和确认密码不一致'
        }
        if(errMsg){
          toast(errMsg, 'warning')
          return;
        }

        this.$loading.show();
        post(api.UPDATE_PASSWORD, this.model).then(data=>{
          toast('修改成功,请重新登录');
          auth.clearToken();
          this.$loading.close();
          this.$router.push('/login')
        }).catch(err=>{
          this.$loading.close();
        })
      }
    }

  }
</script>

<style scoped>

</style>
